<template>
    <form class="login-form" @submit="formSubmit">
        <!-- 手机号输入 -->
        <view class="form-item">
            <input
                class="form-input"
                v-model="formData.phone"
                placeholder="请输入手机号"
                @blur="validatePhone"
            />
            <text class="error-text" v-if="errors.phone">{{
                errors.phone
            }}</text>
        </view>

        <!-- 密码输入 -->
        <view class="form-item">
            <input
                class="form-input"
                v-model="formData.password"
                password
                placeholder="请输入密码"
                @blur="validatePassword"
            />
            <text class="error-text" v-if="errors.password">{{
                errors.password
            }}</text>
        </view>

        <!-- 确认密码 -->
        <view class="form-item">
            <input
                class="form-input"
                v-model="formData.confirmPassword"
                password
                placeholder="请确认密码"
                @blur="validateConfirmPassword"
            />
            <text class="error-text" v-if="errors.confirmPassword">{{
                errors.confirmPassword
            }}</text>
        </view>

        <!-- 操作按钮 -->
        <view class="form-actions">
            <button class="submit-btn" form-type="submit">注册</button>
            <button class="switch-btn" @click="switchToLogin">返回登录</button>
        </view>

        <!-- 协议勾选 -->
        <view class="agreement">
            <label class="checkbox-container">
                <checkbox
                    class="agreement-checkbox"
                    :checked="formData.agreement"
                    @click="toggleAgreement"
                />
                <text class="agreement-text">
                    登录/注册表示您同意
                    <text class="link" @click="openAgreement('user')"
                        >《用户协议》</text
                    >
                    和
                    <text class="link" @click="openAgreement('privacy')"
                        >《隐私政策》</text
                    >
                </text>
            </label>
            <text class="error-text" v-if="errors.agreement">{{
                errors.agreement
            }}</text>
        </view>
    </form>
</template>

<script setup>
// import md5 from 'md5';

import { reactive } from 'vue';
import { useLoginStore } from '../../../stores/loginStores';
import { useUserStore } from '../../../stores/userStores';

const loginStore = useLoginStore();
const userStore = useUserStore();
const emit = defineEmits(['switch-form']);

// 表单数据
const formData = reactive({
    phone: '',
    password: '',
    confirmPassword: '',
    agreement: true
});

// 错误信息
const errors = reactive({
    phone: '',
    password: '',
    confirmPassword: '',
    agreement: ''
});

// 验证规则
const validateRules = {
    phone: (value) => {
        const phoneReg = /^1[3-9]\d{9}$/;
        if (!value) return '请输入手机号';
        if (!phoneReg.test(value)) {
            return '请输入有效的手机号';
        }
        return '';
    },
    password: (value) => {
        if (!value) return '请输入密码';
        if (value.length < 6 || value.length > 20) {
            return '密码长度需为6-20位';
        }
        return '';
    },
    confirmPassword: (value) => {
        if (!value) return '请确认密码';
        if (value !== formData.password) {
            return '两次输入密码不一致';
        }
        return '';
    },
    agreement: (value) => {
        if (!value) return '请同意用户协议和隐私政策';
        return '';
    }
};

// 字段验证方法
const validatePhone = () =>
    (errors.phone = validateRules.phone(formData.phone));
const validatePassword = () =>
    (errors.password = validateRules.password(formData.password));
const validateConfirmPassword = () =>
    (errors.confirmPassword = validateRules.confirmPassword(
        formData.confirmPassword
    ));
const validateAgreement = () =>
    (errors.agreement = validateRules.agreement(formData.agreement));

// 切换协议状态
const toggleAgreement = () => {
    formData.agreement = !formData.agreement;
    validateAgreement();
};

// 表单提交
const formSubmit = () => {
    validatePhone();
    validatePassword();
    validateConfirmPassword();
    validateAgreement();

    const hasErrors = Object.values(errors).some((msg) => msg !== '');

    if (!hasErrors) {
        // console.log('表单提交成功', formData);
        // 执行注册逻辑

        loginStore
            .userRegister({
                phone: formData.phone,
                // userPassword: md5(formData.password.trim())
                password: formData.password
            })
            .then(async (res) => {
                // console.log(res);

                if (res.data.code === 20000) {
                    // 注册成功后自动登录
                    const loginRes = await loginStore.userLogin({
                        phone: formData.phone,
                        password: formData.password
                    });

                    if (loginRes.data.code === 20000) {
                        // 保存用户基础信息
                        userStore.setCurrentBaseUserInfo({
                            token: loginRes.data.data.token,
                            userId: loginRes.data.data.userId
                        });

                        // 获取完整用户信息
                        await userStore.fetchCurrentFullUserInfo();

                        uni.showToast({
                            title: '注册成功',
                            icon: 'success',
                            duration: 2000
                        });

                        // 跳转首页
                        uni.reLaunch({
                            url: '/pages/home/home'
                        });
                    }
                } else {
                    uni.showToast({
                        title: res.data.message,
                        icon: 'none'
                    });

                    formData.password = '';
                    formData.confirmPassword = '';
                }
            });
    } else {
        return false;
    }
};

// 切换表单
const switchToLogin = () => emit('switch-form', 'login');

// 打开协议
const openAgreement = (type) => {
    console.log(`打开${type === 'user' ? '用户协议' : '隐私政策'}`);
};
</script>

<style lang="scss" scoped>
@import 'commonForm.scss';
</style>
